//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  PostActivityBoard.m
//  iHeima
//
//  Created by he chao on 6/3/14.
//  Copyright (c) 2014 leon. All rights reserved.
//

#import "PostActivityBoard.h"
#import <UIKit/UIKit.h>
#pragma mark -

@interface PostActivityBoard()<UITextViewDelegate,UITableViewDelegate,UIScrollViewDelegate>
{
	//<#@private var#>
    
    
    BeeUIScrollView* _scrollView;
    
    BOOL isCouldMove;
}
@end

@implementation PostActivityBoard
DEF_SIGNAL(POST)
DEF_SIGNAL(START)
DEF_SIGNAL(END)
DEF_SIGNAL(CITY)
DEF_SIGNAL(CATEGORY)
DEF_SIGNAL(COVER)
DEF_SIGNAL(LOCAL)
DEF_SIGNAL(CAMERA)

- (void)load
{
    [self getCategory];
    [self getCityList];
}

- (void)unload
{
}

#pragma mark - Signal

ON_CREATE_VIEWS( signal )
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"发布活动";
    [self showBarButton:BeeUINavigationBar.LEFT image:IMAGESTRING(@"navi_back")];
    [self showNaviBar];
    [self loadContent];
    
    
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
}

ON_DID_DISAPPEAR( signal )
{
}

ON_SIGNAL3( BeeUINavigationBar, LEFT_TOUCHED, signal )
{
    [self.stack popBoardAnimated:YES];
}

ON_SIGNAL3( BeeUINavigationBar, RIGHT_TOUCHED, signal )
{
}

ON_SIGNAL2(PostActivityBoard, signal) {
    if ([signal is:PostActivityBoard.POST]) {
        if (![self checkInputData]) {
            return;
        }
        BeeHTTPRequest *request = [self POST:[NSString stringWithFormat:@"%@/apiactivity/publish",kBaseUrl]].PARAM(@"uid",kUserInfo[@"uid"]).PARAM(@"name",fieldName.text).PARAM(@"start_at",[NSString stringWithFormat:@"%ld",start]).PARAM(@"end_at",[NSString stringWithFormat:@"%ld",end]).PARAM(@"province_id",dictProvince[@"id"]).PARAM(@"city_id",dictCity[@"id"]).PARAM(@"address",fieldAddress.text).PARAM(@"trade_id",dictCategory[@"id"]).PARAM(@"intro",textIntro.text);
        if (imgTemp) {
            request.FILE(@"img0",UIImageJPEGRepresentation(imgTemp, 0.4));
        }
    }
    else if ([signal is:PostActivityBoard.START]) {
        BeeUIDatePicker *datePicker = [BeeUIDatePicker spawn];
        datePicker.tag = 9527;
        datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        [datePicker showInViewController:self];
    }
    else if ([signal is:PostActivityBoard.END]) {
        BeeUIDatePicker *datePicker = [BeeUIDatePicker spawn];
        datePicker.tag = 9528;
        datePicker.datePickerMode = UIDatePickerModeDateAndTime;
        [datePicker showInViewController:self];
    }
    else if ([signal is:PostActivityBoard.CITY]) {
        BeeUIPickerView *myPickerView = [BeeUIPickerView spawn];
        [myPickerView setColumns:2];
        myPickerView.tag = 9528;
        for (int i = 0; i < arrayCity.count; i++) {
            [myPickerView addTitle:arrayCity[i][@"name"] forColumn:0];
        }
        //
        
        NSArray *arrayChild = arrayCity[selProvince][@"child"];
        for (int i = 0; i < arrayChild.count; i++) {
            [myPickerView addTitle:arrayChild[i][@"name"] forColumn:1];
        }
        
        //
        
        [myPickerView showInViewController:self];
        
        //        [myPickerView pickerView:myPickerView didSelectRow:selProvince inComponent:0];
        //        [myPickerView pickerView:myPickerView didSelectRow:selCity inComponent:1];
        [myPickerView selectRow:selProvince inComponent:0 animated:YES];
        [myPickerView selectRow:selCity inComponent:1 animated:YES];
        
        [myPickerView setSelRowIndex:selProvince inComponent:0];
        [myPickerView setSelRowIndex:selCity inComponent:1];
    }
    else if ([signal is:PostActivityBoard.CATEGORY]) {
        BeeUIPickerView *myPickerView = [BeeUIPickerView spawn];
        for (int i = 0; i < arrayCategory.count; i++) {
            [myPickerView addTitle:arrayCategory[i][@"name"]];
        }
        myPickerView.tag = 9527;
        [myPickerView selectRow:selCategory inComponent:0 animated:YES];
        [myPickerView showInViewController:self];
    }
    else if ([signal is:PostActivityBoard.COVER]) {
        BeeUIActionSheet *sheet = [BeeUIActionSheet spawn];
        sheet.title = @"请选择操作";
        [sheet addButtonTitle:@"拍照" signal:PostActivityBoard.CAMERA];
        [sheet addButtonTitle:@"从相册选择" signal:PostActivityBoard.LOCAL];
        [sheet addCancelTitle:@"取消"];
        [sheet showInViewController:self];
    }
    else if ([signal is:PostActivityBoard.LOCAL]) {
        UIImagePickerController * c = [[UIImagePickerController alloc] init];
        c.delegate = self;
        c.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //c.allowsEditing = YES;
        [self presentViewController:c animated:YES completion:nil];
    }
    else if ([signal is:PostActivityBoard.CAMERA]) {
        UIImagePickerController * c = [[UIImagePickerController alloc] init];
        c.delegate = self;
        c.sourceType = UIImagePickerControllerSourceTypeCamera;
        //c.allowsEditing = YES;
        [self presentViewController:c animated:YES completion:nil];
    }
}

- (void)handleRequest:(BeeRequest *)request
{
    if(request.failed)
    {
        [[BeeUITipsCenter sharedInstance] dismissTips];
        NETWORK_ERROR
    }
    else if (request.succeed)
    {
        id json = [request.responseString mutableObjectFromJSONString];
        NSLog(@"%@",json);
        switch ([json[@"status"] intValue]) {
            case 1:
            {
                [[BeeUITipsCenter sharedInstance] presentMessageTips:@"发布活动成功!审核通过后为您展示"];
                [self.stack popBoardAnimated:YES];
            }
                break;
        }
    }
}
- (void) registerForKeyboardNotifications{
    //[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardWillHideNotification object:nil];
    
}




//- (void) keyboardWasShown:(NSNotification *) notif{
//    NSDictionary *info = [notif userInfo];
//    
//   
//    
//    NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];
//    CGRect keyBoardRect = [value CGRectValue];
//    int height = keyBoardRect.size.height;
//    int changeY = height-80;
//    float newPointY= _scrollView.contentOffset.y + changeY;
//    
//    [UIView animateWithDuration:.2 animations:^{
//        [_scrollView setContentOffset:CGPointMake(0, newPointY)];
//    }];
//    printf("newY:%.1f",_scrollView.contentOffset.y);
//    
//}
//
- (void) keyboardWasHidden:(NSNotification *) notif{
    
    NSLog(@"键盘隐藏");
    
    [self resumeBg];
    
    
    
}


ON_SIGNAL2(BeeUIDatePicker, signal) {
    BeeUIDatePicker *picker = signal.source;
    NSDate *date = picker.date;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat : @"yyyy-MM-dd hh:mm"];
    NSString *strDate = [formatter stringFromDate:date];
    if (picker.tag == 9527) {
        labelStart.text = strDate;
        start = [date timeIntervalSince1970];
    }
    else {
        labelEnd.text = strDate;
        end = [date timeIntervalSince1970];
    }
}

ON_SIGNAL2(BeeUIPickerView, signal) {
    BeeUIPickerView *picker = (BeeUIPickerView *)signal.source;
    if ([signal is:BeeUIPickerView.CONFIRMED]) {
        switch (picker.tag) {
            case 9527:
            {
                selCategory = [picker selectedRowInComponent:0];
                dictCategory = arrayCategory[selCategory];
                self.strCategory = dictCategory[@"name"];
                
                labelCategory.text = self.strCategory;
                //[self sendUISignal:BeeUIBoard.WILL_APPEAR];
            }
                break;
            case 9528:
            {
                selProvince = [picker selectedRowInColumn:0];
                selCity = [picker selectedRowInColumn:1];
                dictProvince = arrayCity[selProvince];
                dictCity = arrayCity[selProvince][@"child"][selCity];
                self.strCity = [picker selectedTitleInColumn:1];
                
                labelCity.text = [NSString stringWithFormat:@"%@ %@",[picker selectedTitleInColumn:0],[picker selectedTitleInColumn:1]];
                //[self sendUISignal:BeeUIBoard.WILL_APPEAR];
            }
                break;
                
            default:
                break;
        }
    }
    else if ([signal is:BeeUIPickerView.CHANGED]) {
        if (picker.tag == 9528) {
            int index = [picker selectedRowInComponent:0];
            if (index != selProvince) {
                [picker removeTitlesForColumn:1];
                NSArray *arrayCity1 = arrayCity[index][@"child"];
                for (int i = 0; i < [arrayCity1 count]; i++) {
                    [picker addTitle:arrayCity1[i][@"name"] forColumn:1];
                }
                [picker reloadAllComponents];
                
                selProvince = index;
                selCity = 0;
                [picker selectRow:selCity inComponent:1 animated:YES];
            }
            
        }
    }

}

- (BOOL)checkInputData{
    if (fieldName.text.length == 0) {
        [[BeeUITipsCenter sharedInstance] presentMessageTips:@"请输入活动名称"];
        return NO;
    }
    if (labelStart.text.length == 0 || labelEnd.text.length == 0) {
        [[BeeUITipsCenter sharedInstance] presentMessageTips:@"请开始和结束时间"];
        return NO;
    }
    if (labelCity.text.length == 0) {
        [[BeeUITipsCenter sharedInstance] presentMessageTips:@"请选择区域"];
        return NO;
    }
    if (fieldAddress.text.length == 0) {
        [[BeeUITipsCenter sharedInstance] presentMessageTips:@"请输入详细地址"];
        return NO;
    }
    if ([labelCategory.text isEqualToString:@"全部"]|| labelCategory.text.length == 0) {
        [[BeeUITipsCenter sharedInstance] presentMessageTips:@"请选择行业列表"];
        return NO;
    }
    
    if (textIntro.text.length == 0) {
        [[BeeUITipsCenter sharedInstance] presentMessageTips:@"活动介绍不能为空"];
        return NO;
    }
    
    return YES;
}

- (void)getCityList{
    id value = [[BeeFileCache sharedInstance] objectForKey:@"city"];
    if (value) {
        arrayCity = [(NSData *)value objectFromJSONData];
        NSLog(@"%@",arrayCity);
    }
    else {

    }
}

- (void)getCategory{
    id value = [[BeeFileCache sharedInstance] objectForKey:@"category"];
    if (value) {
        arrayCategory = [(NSData *)value objectFromJSONData];
        NSLog(@"%@",arrayCategory);
    }
    else {
    }
}





- (void)loadContent{
    
    [self registerForKeyboardNotifications];
    
    self.view.backgroundColor = RGB(246, 246, 246);
    isCouldMove = YES;
    
    _scrollView = [BeeUIScrollView spawn];
    _scrollView.delegate = self;
    _scrollView.frame = CGRectMake(0, 0, self.viewWidth, self.viewHeight-(IOS7_OR_LATER?64:44));
    [self.view addSubview:_scrollView];
    
    BeeUIImageView *coverBg = [BeeUIImageView spawn];
    coverBg.frame = CGRectMake(0, 0, self.viewWidth, 175);
    coverBg.backgroundColor = [UIColor whiteColor];
    coverBg.userInteractionEnabled = YES;
    [_scrollView addSubview:coverBg];

    imgCover = [BeeUIImageView spawn];
    imgCover.contentMode = UIViewContentModeScaleAspectFill;
    imgCover.frame = CGRectMake(0, 0, 290, 153);
    imgCover.image = IMAGESTRING(@"cover_default");
    imgCover.center = CGPointMake(coverBg.width/2.0, coverBg.height/2.0);
    [imgCover makeTappable:PostActivityBoard.COVER];
    [coverBg addSubview:imgCover];
    
    UIView *line1 = [self createLine];
    line1.frame = CGRectMake(0, coverBg.bottom-0.5, line1.width, line1.height);
    [coverBg addSubview:line1];
    
    fieldName = [BeeUITextField spawn];
    
    //  键盘的样式
    [fieldName addTarget:self action:@selector(RESIGH) forControlEvents:UIControlEventEditingDidEndOnExit];
    fieldName.returnKeyType = UIReturnKeyDone;
   
    
    fieldName.frame = CGRectMake(0, coverBg.bottom+20, self.viewWidth, 44);
    fieldName.backgroundColor = [UIColor whiteColor];
    fieldName.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    fieldName.placeholder = @"在此输入活动名称";
    fieldName.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 20, 0)];
    fieldName.leftViewMode = UITextFieldViewModeAlways;
    fieldName.font = FONT(14);
    [_scrollView addSubview:fieldName];
    
    NSArray *titles = @[@"开始时间",@"结束时间",@"区域",@"",@"行业类别"];
    for (int i = 0; i < 8; i++) {
        if (i<3 || i==4) {
            BeeUIButton *btn = [BeeUIButton spawn];
            btn.frame = CGRectMake(0, fieldName.bottom+20+i*44, self.viewWidth, 44);
            if (i==4) {
                btn.frame = CGRectMake(0, fieldName.bottom+40+(i)*44, self.viewWidth, 44);
            }
            btn.backgroundColor = [UIColor whiteColor];
            [_scrollView addSubview:btn];
            
            BeeUIImageView *icon = [BeeUIImageView spawn];
            icon.frame = CGRectMake(10, 0, 30, 44);
            NSString *strIcon = [NSString stringWithFormat:@"post_activity_icon%d",i];
            icon.image = IMAGESTRING(strIcon);
            [btn addSubview:icon];
            
            BaseLabel *title = [BaseLabel initLabel:titles[i] font:FONT(14) color:kNormalColor textAlignment:NSTextAlignmentLeft];
            title.frame = CGRectMake(icon.right, 0, 200, 44);
            [btn addSubview:title];
            
            switch (i) {
                case 0:
                {
                    [btn addSignal:PostActivityBoard.START forControlEvents:UIControlEventTouchUpInside];
                    
                    labelStart = [BaseLabel initLabel:@"" font:FONT(14) color:[UIColor blackColor] textAlignment:NSTextAlignmentRight];
                    labelStart.frame = CGRectMake(0, 0, 300, 44);
                    [btn addSubview:labelStart];
                }
                    break;
                case 1:
                {
                    [btn addSignal:PostActivityBoard.END forControlEvents:UIControlEventTouchUpInside];
                    labelEnd = [BaseLabel initLabel:@"" font:FONT(14) color:[UIColor blackColor] textAlignment:NSTextAlignmentRight];
                    labelEnd.frame = CGRectMake(0, 0, 300, 44);
                    [btn addSubview:labelEnd];
                }
                    break;
                case 2:
                {
                    [btn addSignal:PostActivityBoard.CITY forControlEvents:UIControlEventTouchUpInside];
                    labelCity = [BaseLabel initLabel:@"" font:FONT(14) color:[UIColor blackColor] textAlignment:NSTextAlignmentRight];
                    labelCity.frame = CGRectMake(0, 0, 300, 44);
                    [btn addSubview:labelCity];
                }
                    break;
                case 4:
                {
                    [btn addSignal:PostActivityBoard.CATEGORY forControlEvents:UIControlEventTouchUpInside];
                    labelCategory = [BaseLabel initLabel:@"" font:FONT(14) color:[UIColor blackColor] textAlignment:NSTextAlignmentRight];
                    labelCategory.frame = CGRectMake(0, 0, 300, 44);
                    [btn addSubview:labelCategory];
                }
                    break;
                    
                default:
                    break;
            }
        }
        else if (i==3){
            fieldAddress = [BeeUITextField spawn];
            fieldAddress.frame = CGRectMake(0, fieldName.bottom+20+i*44, self.viewWidth, 44);
            fieldAddress.backgroundColor = [UIColor whiteColor];
            fieldAddress.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            fieldAddress.placeholder = @"输入详细地址";
            fieldAddress.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 40, 0)];
            fieldAddress.leftViewMode = UITextFieldViewModeAlways;
            fieldAddress.font = FONT(14);
            [_scrollView addSubview:fieldAddress];
            
            
            [fieldAddress addTarget:self action:@selector(RESIGH) forControlEvents:UIControlEventEditingDidEndOnExit];
            fieldAddress.returnKeyType=UIReturnKeyDone;
        }
        
        UIView *line = [self createLine];
        [_scrollView addSubview:line];
        if (i<5) {
            line.frame = CGRectMake(0, fieldName.bottom+20+i*44, self.viewWidth, line.height);
        }
        else if (i<7) {
            line.frame = CGRectMake(0, fieldName.bottom+40+(i-1)*44, self.viewWidth, line.height);
        }
        else {
            UIView *bg = [[UIView alloc] initWithFrame:CGRectMake(0, fieldName.bottom+40+5*44+0.5, self.viewWidth, 139)];
            bg.backgroundColor = [UIColor whiteColor];
            [_scrollView addSubview:bg];
            
            BeeUIImageView *icon = [BeeUIImageView spawn];
            icon.frame = CGRectMake(10, fieldName.bottom+40+5*44, 30, 44);
            icon.image = IMAGESTRING(@"post_activity_icon5");
            [_scrollView addSubview:icon];
            
            UILabel* label = [[UILabel alloc]initWithFrame:CGRectMake(40, icon.y+10, 100, 20)];
            label.text = @"活动介绍";
            label.textColor = [UIColor grayColor];
            label.font = [UIFont systemFontOfSize:14];
            [_scrollView addSubview:label];
            
            textIntro = [BeeUITextView spawn];
            textIntro.frame = CGRectMake(35, fieldName.bottom+40+5*44+5+20, 270, 139);
            textIntro.font = FONT(14);
           // textIntro.placeholder = @"活动介绍";
            [_scrollView addSubview:textIntro];
 
            textIntro.returnKeyType=UIReturnKeyDone;
            [textIntro resignFirstResponder];
            
            textIntro.delegate = self;
            
            
            
            line.frame = CGRectMake(0, fieldName.bottom+40+5*44+140, self.viewWidth, line.height);
            
        }
    }
    
    BaseButton *btn = [BaseButton initBaseBtn:IMAGESTRING(@"btn1") highlight:IMAGESTRING(@"btn1_pre") text:@"提交活动" textColor:[UIColor whiteColor] font:FONT(14)];
    btn.frame = CGRectMake(65, textIntro.bottom+20, 190, 44);
    [btn addSignal:PostActivityBoard.POST forControlEvents:UIControlEventTouchUpInside];
    [_scrollView addSubview:btn];
    
    [_scrollView setContentSize:CGSizeMake(self.viewWidth, btn.bottom+20)];
}



- (BOOL)textViewShouldBeginEditing:(UITextView *)textView{
    
    if (isCouldMove) {
        NSTimeInterval animationDuration=0.30f;
        [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
        [UIView setAnimationDuration:animationDuration];
        float width = self.view.frame.size.width;
        float height = self.view.frame.size.height;
        //上移30个单位，按实际情况设置
        CGRect rect=CGRectMake(0.0f,-60,width,height);
        self.view.frame=rect;
        
        [UIView commitAnimations];
    }
    
    isCouldMove = NO;
    
    
    return YES;
}

- (void)resumeBg{
    
    NSTimeInterval animationDuration=0.30f;
    [UIView beginAnimations:@"ResizeForKeyboard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width = self.view.frame.size.width;
    float height = self.view.frame.size.height;
   
    CGRect rect=CGRectMake(0.0f,60.0f,width,height);
    self.view.frame=rect;
    [UIView commitAnimations];
   
    isCouldMove = YES;
    
    
}



- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text {
    if ([text isEqualToString:@"\n"]) {
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
}







- (UIView *)createLine{
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.viewWidth, 0.5)];
    line.backgroundColor = RGB(187, 187, 187);
    return line;
}

- (void)imagePickerController:(UIImagePickerController *)imagePickerController didFinishPickingMediaWithInfo:(id)info
{
    
    UIImage * i = [info[@"UIImagePickerControllerOriginalImage"] copy];
    if(i.size.width > 640)
    {
        i = [self scaleImage:i toScale:640/i.size.width];
    }
    
    [self dismissViewControllerAnimated:YES completion:NULL];
    //[self sendImage:i];
    imgTemp = i;
    imgCover.image = i;
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)imagePickerController
{
    NSLog(@"Cancelled");
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}
-(void)RESIGH
{
    [fieldName resignFirstResponder];
    
}


@end
